import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:smart_ai_dart/consts/index.dart';
import 'package:smart_ai_dart/utils/storage.dart';
import 'package:smart_ai_dart/utils/log_utils.dart';
import 'dart:convert';

extension ThemeExtension on BuildContext {
  bool get isDark => AppTheme.isDark(this);
  Color get dialogBackgroundColor => Theme.of(this).canvasColor;
  Color get backgroundColor => Theme.of(this).scaffoldBackgroundColor;
}

class AppTheme {
  static final AppTheme shared = AppTheme._internal();
  bool _isInitialized = false;
  late ThemeMode _themeMode;
  late Map<String, dynamic> _themeConfig;
  // final String _themeKey = 'app_theme_mode';
  final ValueNotifier<ThemeMode> themeNotifier =
      ValueNotifier(ThemeMode.system);

  static bool isDark(BuildContext context) {
    return Theme.of(context).brightness == Brightness.dark;
  }

  static Color? getIconColor(BuildContext context) {
    return isDark(context) ? ColorEums.dark_text : null;
  }

  static Color? getDarkColor(BuildContext context, Color darkColor) {
    return isDark(context) ? darkColor : null;
  }

  factory AppTheme() {
    return shared;
  }

  AppTheme._internal();

  Future<void> init() async {
    if (_isInitialized) {
      LogUtils.shared.w('AppTheme has already been initialized');
      return;
    }

    // 从存储中读取主题设置
    // final savedTheme = StorageUtils.shared.getString(_themeKey);
    // _themeMode = _getThemeModeFromString(savedTheme);

    try {
      // 读取配置文件
      final String configString =
          await rootBundle.loadString('assets/jsons/theme.json');
      _themeConfig = json.decode(configString);

      // 设置主题模式
      _themeMode = _getThemeModeFromString(_themeConfig['themeMode']);
      themeNotifier.value = _themeMode;

      _isInitialized = true;
      LogUtils.shared.i('AppTheme initialized successfully');
    } catch (e, stack) {
      LogUtils.shared.e('AppTheme initialization failed', e, stack);
      // 使用默认配置
      _themeMode = ThemeMode.system;
      themeNotifier.value = _themeMode;
      _themeConfig = {
        'dark': _defaultDarkConfig,
        'light': _defaultLightConfig,
      };
    }
  }

  // 默认亮色主题配置
  Map<String, String> get _defaultLightConfig => {
        'primaryColor': '#2196F3',
        'appBarColor': '#2196F3',
        'cardColor': '#FFFFFF',
        'textColor': '#000000',
        'scaffoldBackgroundColor': '#FFFFFF',
      };

  // 默认暗色主题配置
  Map<String, String> get _defaultDarkConfig => {
        'primaryColor': '#1976D2',
        'appBarColor': '#1F1F1F',
        'cardColor': '#242424',
        'textColor': '#FFFFFF',
        'scaffoldBackgroundColor': '#121212',
      };

  static const SystemUiOverlayStyle light = SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: ColorEums.dark_bg_color,
    statusBarIconBrightness: Brightness.light,
    statusBarBrightness: Brightness.dark,
    systemNavigationBarIconBrightness: Brightness.light,
  );

  static const SystemUiOverlayStyle dark = SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: Colors.white,
    statusBarIconBrightness: Brightness.dark,
    statusBarBrightness: Brightness.light,
    systemNavigationBarIconBrightness: Brightness.dark,
  );

  void _checkInitialization() {
    if (!_isInitialized) {
      throw Exception(
          'AppTheme has not been initialized. Call AppTheme.shared.init() first.');
    }
  }

  // 将十六进制颜色字符串转换为 Color 对象
  Color _hexToColor(String hexString) {
    final hex = hexString.replaceFirst('#', '');
    return Color(int.parse('FF$hex', radix: 16));
  }

  ThemeMode get themeMode {
    _checkInitialization();
    return _themeMode;
  }

  Future<void> setThemeMode(ThemeMode mode) async {
    _checkInitialization();
    _themeMode = mode;
    themeNotifier.value = mode;

    // 更新配置文件中的主题模式
    _themeConfig['themeMode'] = mode.toString();
    LogUtils.shared.i('Theme mode updated: $mode');
  }

  Future<void> toggleTheme() async {
    _checkInitialization();
    if (_themeMode == ThemeMode.dark) {
      await setThemeMode(ThemeMode.light);
    } else {
      await setThemeMode(ThemeMode.dark);
    }
  }

  ThemeMode _getThemeModeFromString(String? themeModeString) {
    switch (themeModeString) {
      case 'ThemeMode.light':
        return ThemeMode.light;
      case 'ThemeMode.dark':
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }

  ThemeData get lightTheme {
    _checkInitialization();
    final lightConfig = _themeConfig['light'];

    return ThemeData(
      brightness: Brightness.light,
      primaryColor: _hexToColor(lightConfig['primaryColor']),
      scaffoldBackgroundColor:
          _hexToColor(lightConfig['scaffoldBackgroundColor']),
      appBarTheme: AppBarTheme(
        backgroundColor: _hexToColor(lightConfig['appBarColor']),
        foregroundColor: _hexToColor(lightConfig['textColor']),
        elevation: 0,
      ),
      cardTheme: CardTheme(
        color: _hexToColor(lightConfig['cardColor']),
        elevation: 2,
        margin: const EdgeInsets.all(8),
      ),
      textTheme: TextTheme(
        bodyLarge: TextStyle(color: _hexToColor(lightConfig['textColor'])),
        bodyMedium: TextStyle(color: _hexToColor(lightConfig['textColor'])),
      ),
    );
  }

  ThemeData get darkTheme {
    _checkInitialization();
    final darkConfig = _themeConfig['dark'];

    return ThemeData(
      brightness: Brightness.dark,
      primaryColor: _hexToColor(darkConfig['primaryColor']),
      scaffoldBackgroundColor:
          _hexToColor(darkConfig['scaffoldBackgroundColor']),
      appBarTheme: AppBarTheme(
        backgroundColor: _hexToColor(darkConfig['appBarColor']),
        foregroundColor: _hexToColor(darkConfig['textColor']),
        elevation: 0,
      ),
      cardTheme: CardTheme(
        color: _hexToColor(darkConfig['cardColor']),
        elevation: 2,
        margin: const EdgeInsets.all(8),
      ),
      textTheme: TextTheme(
        bodyLarge: TextStyle(color: _hexToColor(darkConfig['textColor'])),
        bodyMedium: TextStyle(color: _hexToColor(darkConfig['textColor'])),
      ),
    );
  }
}
